const args = process.argv;
const path = require('path');
const fs = require('fs');

const shell = require('shelljs');
const readThemeRegistry = require('./lib/ReadThemeRegistry');

let themeName = args[2];
if (!themeName) {
  shell.echo('❌ Please enter a theme name as argument');
  shell.exit(1);
}

if (themeName.toLowerCase().endsWith('theme')) {
  // Remove unnecessary trailing "Theme" from input
  // eg: "Foo Bar" => "Foo Bar", "Foo Theme" => "Foo", "FooTheme" => "Foo"
  const lastIndex = themeName.toLowerCase().lastIndexOf('theme');
  themeName = themeName.slice(0, lastIndex).trim();
}

// Remove spaces and append 'Theme' to get full theme identifier
// eg: "Foo Bar" => "FooBarTheme"
const themeId = themeName.replace(/\s+/, '') + 'Theme';


const dir = path.resolve(__dirname, '../src/UI/Theme/', themeId);
if (fs.existsSync(dir)) {
  shell.echo('❌ Theme `' + themeName + '` already exists');
  process.exit(0);
}

// Create Theme Folder
fs.mkdirSync(dir);
shell.echo('✅ Created Folder', dir);

// Create Style Library
fs.writeFileSync(
  path.resolve(dir, 'theme.json'),
  fs.readFileSync(path.resolve(__dirname, './theme-templates/theme.json')).toString(),
);
shell.echo('✅ Created theme.json');

// Create Theme Object
fs.writeFileSync(
  path.resolve(dir, 'index.js'),
  fs.readFileSync(path.resolve(__dirname, './theme-templates/index.js')).toString().replace(/\$THEME_ID/g, themeId),
);
shell.echo('✅ Created index.js');

// Re-write ThemeRegistry
const registry = readThemeRegistry()
  .concat({
    id: themeId,
    name: themeName,
  });

const imports =
  registry.map(it => `import ${it.id} from './${it.id}';`).join('\n');

const themes =
  registry.map(it => `    ['${it.name}']: ${it.id},`).join('\n');

const disclaimer = '// This file is generated by create-new-theme.js script';

fs.writeFileSync(
  path.resolve(dir, '../ThemeRegistry.js'),
  disclaimer + '\n' + imports + '\n\n/*eslint no-useless-computed-key: "off"*/\nexport const themes = {\n' + themes + '\n};',
);
shell.echo('✅ Updated ThemeRegistry.js');

// Recompile Style Resources
const output = shell.exec(`node ${__dirname}/build-theme-resources.js`);
if (output.code !== 0) {
  shell.echo(
    '❌ Unable to build the theme resources. Error is:',
  );
  shell.echo(output.stdout);
  shell.echo(output.stderr);
  shell.exit(output.code);
}

shell.echo('✅ Themes resources built');
